package com.yilee.idouban.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.yilee.idouban.bean.Person;

public class DbHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "idouban.db";
	private static final int DATABASE_VERSION = 1;
	private Dao<Person, Integer> personDao;

	public DbHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
		try {
			TableUtils.createTable(connectionSource, Person.class);
		} catch (Exception e) {
			Log.e(DbHelper.class.getName(), "Unable to create Person datbases",
					e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqliteDatabase,
			ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, Person.class, true);
			onCreate(sqliteDatabase, connectionSource);
		} catch (Exception e) {
			Log.e(DbHelper.class.getName(),
					"Unable to upgrade Person database from version " + oldVer
							+ " to new " + newVer, e);
		}
	}

	public Dao<Person, Integer> getPersonDao() throws Exception {
		if (personDao == null) {
			personDao = getDao(Person.class);
		}
		return personDao;
	}

}
